#!/usr/bin/python
# -*- coding: UTF-8 -*-

import urllib3
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher 
from urllib import parse
import httpx
from PJ import log
urllib3.disable_warnings()
#登录获取token
class YH():
    def __init__(self,userNo:str):
        self.userNo = userNo
        url = "https://cas.paas.cdut.edu.cn/cas/login?service=http://jxpc.cdut.edu.cn/base/login/return?type=mobile"     
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"}
        try:
            res = httpx.get(url=url,headers=headers,timeout=5)
            #res=requests.get(url=url,headers=headers)
            self.ck = res.cookies
            #tem=res.cookies.items()
            #print(tem)
            #self.session = "SESSION=" +tem[0][1]+";"
        except Exception as e:
            log({"code":-101,"msg":f'getSessionId错误：{e}'}) 
            exit()

    def getpublicKey(self):
        #pwd = self.pwd
        try:
            #res=requests.get('https://cas.paas.cdut.edu.cn/cas/jwt/publicKey')
            _t = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyor3CX6A6U4EoSHawtALiJoB0CkJnb/wmVkcVT5EmNupGVrVSeJo80ZAxsgd9S1CZVXxTXtJ7XjsqnzR64Qvrn+tdvj9Ck5k/6Tnp6HoKU/AQxA3tQ5Zqw6D6ihPOyVV4z4cdK5wjzEBNPhJuTjjzP4VQ4h4VseWNbfhXGK3vSes8oNn5Wwor9r1UbEJP/ZMHrDJxAcwe0GPvebAqEp4O5ZcTtWnq+/qkoUB6z/52EnCMltoPmuMC+o3fWdICBf4q70oSDClfuhLVi4mRT2K5UUH8fsxEe6oPtkvk9vVCCOZRmo0MXpXZiIqdZOtgcBzn/0mzoNd58KxeIy0ginjfwIDAQAB\n-----END PUBLIC KEY-----"
            public_key=RSA.importKey(_t)
            cipher = PKCS1_cipher.new(public_key)  # 生成一个加密的类
            encrypt_text = base64.b64encode(cipher.encrypt(pwd.encode()))  # 对数据进行加密
            pwd="__RSA__"+encrypt_text.decode()
            #pwd = "__RSA__mA5DG+t9jBODfE5bw1ptuYtiYbxqWPhjZfK5+rGYqliy3bSRcK5UxXYkwlMfH/qBpV5VuvjaZ9DzfzGjPRZl3ivA4xg5PiKIRqUOb4De387p0dxIhrbVmFuYbEVPz7845qq6816O+U0ZmOiAOkEYMKmjxTh6k+Ofr+w5I2YdLnu5IncG5v5xbptEwsUQoDaeFCX/RuHHLyO3rGSChlZ3LGP6P7kjlfb9gMiHxTkQKfvs99KfbXsHQ9cEwgI6QNedY8HsWhOKJoe5xrWUSSs45MiEI0rFVmNsiiyUSJAHbzGHnKfCmpV0A4F1HuasMjASsBfX3RPIUt2kXHUtXtfPVA=="
            pwd=parse.quote(pwd)
            #del res
        except Exception as e:
            print({"code":-102,"msg":'getpublicKey错误：'+str(e)}) 
            return ""
        data = f"username={self.userNo}&password={pwd}&captcha=&currentMenu=1&failN=0&mfaState=&execution=e1s1&_eventId=submit&geolocation=&submit=%E7%99%BB%E5%BD%95"
        print(data)
        return data
    
    def login_1(self,data):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            #"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            #"Cache-Control": "max-age=0",
            "Content-Length": str(len(data)),
            "Content-Type": "application/x-www-form-urlencoded",
            #"Cookie": self.session,
            #"Origin": "https://cas.paas.cdut.edu.cn",
            "Referer": "https://cas.paas.cdut.edu.cn/cas/login?service=http://jxpc.cdut.edu.cn/base/login/return?type=mobile",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/117.0.0.0"
        }
        loginurl = "https://cas.paas.cdut.edu.cn/cas/login?service=http://jxpc.cdut.edu.cn/base/login/return?type=mobile"
        res = httpx.post(url=loginurl,headers=headers,data=data,follow_redirects=False,cookies=self.ck,timeout=5)
        #res = requests.post(url=loginurl,headers=headers,data=data,allow_redirects=False,verify=False,cookies=self.ck)
        #print(res.text)
        #print(res.headers)
        return res.headers['Location']

    def login_2(self,url):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Host": "jxpc.cdut.edu.cn",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/117.0.0.0"
            }

        res = httpx.get(url=url,headers=headers,follow_redirects=False,timeout=5)
        JSESSIONID = res.cookies
        #headers.update({"Cookie": f"JSESSIONID={JSESSIONID};"})
        res = httpx.get(url=res.headers['Location'],headers=headers,follow_redirects=False,cookies=JSESSIONID,timeout=5)
        tem=res.cookies
        return tem.get("token","")
    
    def yhlogin(self,pwd):
        _pwd = f"__RSA__{pwd}"
        data = f"username={self.userNo}&password={_pwd}&captcha=&currentMenu=1&failN=0&mfaState=&execution=e1s1&_eventId=submit&geolocation=&submit=%E7%99%BB%E5%BD%95"
        url = self.login_1(data)
        token = self.login_2(url)
        return token

def yhlogin(userNo,pwd):
    try:
        yh = YH(userNo)
        log(f"{userNo}----{pwd}")
        return yh.yhlogin(pwd)
    except Exception as e:
        log(f"登录出错{userNo}: {e}")
        return ""